﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataCentral.Forms;
using DataCentral.Dataset;
using CommonData;
using DataCentral.Dataset.DataCentralDatasetTableAdapters;
using System.Collections;
using DevExpress.XtraTab;

namespace DataCentral.UserControls
{
    public partial class SalePersonDebtControl : DataCentral.CommonCenterControl
    {
        ValueListClass clValueList = new ValueListClass();
        public SalePersonDebtControl()
        {
            InitializeComponent();
        }

        #region Sale Person
        private void UpdateValueOfDebtSalePersonRow(DataCentralDataset.DebtSalePersonRow drDebtSalePerson, DataCentralDataset.SalespersonRow drSalePerson, DataTable tblPreviousDebt)
        {
            drDebtSalePerson.SalePersonID = drSalePerson.SalePersonID;
            drDebtSalePerson.FromDate = dtpFromDate.DateTime.Date;
            drDebtSalePerson.ToDate = dtpToDate.DateTime.Date;

            //Get first debt
            DataRow[] lstFirst = tblPreviousDebt.Select("SalePersonID = " + drSalePerson.SalePersonID);
            if (rdgDebtOption.SelectedIndex ==0)
            {
                if (lstFirst.Length > 0 && !string.IsNullOrEmpty(lstFirst[0]["LastDebt"].ToString()))
                {
                    drDebtSalePerson.FirstDebt = Convert.ToDecimal(lstFirst[0]["LastDebt"]);
                    drDebtSalePerson.FirstDescription = "Chuyển từ công nợ cuối kỳ trước sang.";
                }
                else
                {
                    drDebtSalePerson.FirstDebt = 0;
                    drDebtSalePerson.FirstDescription = "Không có giá trị";
                }
            }

            //Get buying value and Paid Value
            decimal dBuying = 0;
            DataRow[] lstBuyingValue = dsCentral.ARSaleDoc.Select("SalePersonID = " + drSalePerson.SalePersonID);
            for (int i = 0; i < lstBuyingValue.Length; i++)
            {
                if (!string.IsNullOrEmpty(lstBuyingValue[0]["CurryOrdAmt"].ToString()))
                    dBuying += Convert.ToDecimal(lstBuyingValue[0]["CurryOrdAmt"]);
            }
            drDebtSalePerson.BuyingValue = dBuying;

            //Get Paid Value
            decimal dPaidValue = 0;
            DataRow[] lstPaidValue = dsCentral.DebtAdjust.Select("SalePersonID = " + drSalePerson.SalePersonID);
            for (int i = 0; i < lstPaidValue.Length; i++)
            {
                if (!string.IsNullOrEmpty(lstPaidValue[0]["PayAmount"].ToString()))
                    dPaidValue += Convert.ToDecimal(lstPaidValue[0]["PayAmount"]);
            }
            drDebtSalePerson.PaidValue = dPaidValue;

            drDebtSalePerson.LastDebt = drDebtSalePerson.FirstDebt + dBuying - dPaidValue;
            drDebtSalePerson.Description = string.Empty;
        }

        private void CalculateDebtSalePerson()
        {
            Hashtable haProcessed = new Hashtable();
            CommonDataAccess cmDataAccess = new CommonDataAccess();
            //Lay thong tin cua ky truoc
            List<ParameterObject> lstParams = new List<ParameterObject>();
            lstParams.Add(new ParameterObject("@ToDate",dtpFromDate.DateTime.Date.AddDays(-1)));
            DataTable tblPreviousDebt = cmDataAccess.GetDataTableBySproc("DATA_GetPreviousSalePersonDebt",lstParams);

            //Tinh tien phai thu trong ky
            ARSaleDocTableAdapter daARDoc = new ARSaleDocTableAdapter();
            daARDoc.Fill(dsCentral.ARSaleDoc, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);

            //Tinh tien da thu trong ky
            DebtAdjust_DateTableAdapter daDebtAdjust = new DebtAdjust_DateTableAdapter();
            daDebtAdjust.Fill(dsCentral.DebtAdjust_Date, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);

            SalespersonTableAdapter daSalePerson = new SalespersonTableAdapter();
            daSalePerson.Fill(dsCentral.Salesperson);
            
            //Trong datatable nay du lieu da duoc sap xep theo ngay tu lon den nho
            foreach(DataCentralDataset.DebtSalePersonRow drDebtPer in dsCentral.DebtSalePerson)
            {
                if (!haProcessed.ContainsKey(drDebtPer.SalePersonID))
                    haProcessed.Add(drDebtPer.SalePersonID,drDebtPer);
            }

            DataCentralDataset.DebtSalePersonRow drDebtSalePerson = null;
            foreach (DataCentralDataset.SalespersonRow drSalePerson in dsCentral.Salesperson)
            {
                if (!haProcessed.ContainsKey(drSalePerson.SalePersonID))
                {
                    drDebtSalePerson = dsCentral.DebtSalePerson.NewDebtSalePersonRow();
                    UpdateValueOfDebtSalePersonRow(drDebtSalePerson, drSalePerson,tblPreviousDebt);
                    dsCentral.DebtSalePerson.AddDebtSalePersonRow(drDebtSalePerson);
                    haProcessed.Add(drSalePerson.SalePersonID, drDebtSalePerson);
                }
                else
                {
                    drDebtSalePerson = (DataCentralDataset.DebtSalePersonRow)haProcessed[drSalePerson.SalePersonID];
                    UpdateValueOfDebtSalePersonRow(drDebtSalePerson, drSalePerson, tblPreviousDebt);
                }
            }
            daDebtSalePerson.Update(dsCentral.DebtSalePerson);
        }
        #endregion

        #region Customer
        private void UpdateValueOfDebtCustomerRow(DataCentralDataset.DebtCustomerRow drDebtCustomer, DataCentralDataset.CustomerRow drCustomer, DataTable tblPreviousDebt)
        {
            drDebtCustomer.CustomerID = drCustomer.CustomerID;
            drDebtCustomer.FromDate = dtpFromDate.DateTime.Date;
            drDebtCustomer.ToDate = dtpToDate.DateTime.Date;

            //Get first debt
            DataRow[] lstFirst = tblPreviousDebt.Select("CustomerID = " + drCustomer.CustomerID);
            if (rdgDebtOption.SelectedIndex == 0)
            {
                if (lstFirst.Length > 0 && !string.IsNullOrEmpty(lstFirst[0]["LastDebt"].ToString()))
                {
                    drDebtCustomer.FirstDebt = Convert.ToDecimal(lstFirst[0]["LastDebt"]);
                    drDebtCustomer.FirstDescription = "Chuyển từ công nợ cuối kỳ trước sang.";
                }
                else
                {
                    drDebtCustomer.FirstDebt = 0;
                    drDebtCustomer.FirstDescription = "Không có giá trị";
                }
            }

            else if (drDebtCustomer.IsFirstDebtNull())
                drDebtCustomer.FirstDebt = 0;

            //Get buying value and Paid Value
            decimal dBuying = 0;
            DataRow[] lstBuyingValue = dsCentral.ARSaleDoc.Select("CustomerID = " + drCustomer.CustomerID);
            for (int i = 0; i < lstBuyingValue.Length; i++)
            {
                if (!string.IsNullOrEmpty(lstBuyingValue[0]["CurryOrdAmt"].ToString()))
                    dBuying += Convert.ToDecimal(lstBuyingValue[0]["CurryOrdAmt"]);
            }
            drDebtCustomer.BuyingValue = dBuying;

            //Get Paid Value
            decimal dPaidValue = 0;
            DataRow[] lstPaidValue = dsCentral.DebtAdjust.Select("CustomerID = " + drCustomer.CustomerID);
            for (int i = 0; i < lstPaidValue.Length; i++)
            {
                if (!string.IsNullOrEmpty(lstPaidValue[0]["PayAmount"].ToString()))
                    dPaidValue += Convert.ToDecimal(lstPaidValue[0]["PayAmount"]);
            }
            drDebtCustomer.PaidValue = dPaidValue;

            drDebtCustomer.LastDebt = drDebtCustomer.FirstDebt + dBuying - dPaidValue;
            drDebtCustomer.Description = string.Empty;
        }

        private void CalculateDebtCustomer()
        {
            Hashtable haProcessed = new Hashtable();
            CommonDataAccess cmDataAccess = new CommonDataAccess();
            //Lay thong tin cua ky truoc
            List<ParameterObject> lstParams = new List<ParameterObject>();
            lstParams.Add(new ParameterObject("@ToDate",dtpFromDate.DateTime.Date.AddDays(-1)));
            DataTable tblPreviousDebt = cmDataAccess.GetDataTableBySproc("DATA_GetPreviousCustomerDebt",lstParams);

            //Tinh tien phai thu trong ky
            ARSaleDocTableAdapter daARDoc = new ARSaleDocTableAdapter();
            daARDoc.Fill(dsCentral.ARSaleDoc, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);

            //Tinh tien da thu trong ky
            DebtAdjust_DateTableAdapter daDebtAdjust = new DebtAdjust_DateTableAdapter();
            daDebtAdjust.Fill(dsCentral.DebtAdjust_Date, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);

            CustomerTableAdapter daCustomer = new CustomerTableAdapter();
            daCustomer.Fill(dsCentral.Customer);
            
            //Trong datatable nay du lieu da duoc sap xep theo ngay tu lon den nho
            foreach(DataCentralDataset.DebtCustomerRow drDebtCus in dsCentral.DebtCustomer)
            {
                if (!haProcessed.ContainsKey(drDebtCus.CustomerID))
                    haProcessed.Add(drDebtCus.CustomerID,drDebtCus);
            }

            DataCentralDataset.DebtCustomerRow drDebtCustomer = null;
            foreach (DataCentralDataset.CustomerRow drCustomer in dsCentral.Customer)
            {
                if (!haProcessed.ContainsKey(drCustomer.CustomerID))
                {
                    drDebtCustomer = dsCentral.DebtCustomer.NewDebtCustomerRow();
                    UpdateValueOfDebtCustomerRow(drDebtCustomer, drCustomer,tblPreviousDebt);
                    dsCentral.DebtCustomer.AddDebtCustomerRow(drDebtCustomer);
                    haProcessed.Add(drCustomer.CustomerID, drDebtCustomer);
                }
                else
                {
                    drDebtCustomer = (DataCentralDataset.DebtCustomerRow)haProcessed[drCustomer.CustomerID];
                    UpdateValueOfDebtCustomerRow(drDebtCustomer, drCustomer, tblPreviousDebt);
                }
            }
            daDebtCustomer.Update(dsCentral.DebtCustomer);
        }
        #endregion

        private void SalePersonDebtControl_Load(object sender, EventArgs e)
        {
            dtpFromDate.DateTime = DateTime.Now.Date;
            dtpToDate.DateTime = DateTime.Now.Date;
            iluSalePerson.DataSource = clValueList.GetSaleSysPersonList();
            iluCustomer.DataSource = clValueList.GetCustomerList();
            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                daDebtSalePerson.Fill(dsCentral.DebtSalePerson, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
            }
            else
            {
                daDebtCustomer.Fill(dsCentral.DebtCustomer, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
            }
        }

        private void tabControl_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                daDebtSalePerson.Fill(dsCentral.DebtSalePerson, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
                iluSalePerson.DataSource = clValueList.GetSaleSysPersonList();
            }
            else
            {
                daDebtCustomer.Fill(dsCentral.DebtCustomer, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
                iluCustomer.DataSource = clValueList.GetCustomerList();
            }
        }

        private void btnShow_Click(object sender, EventArgs e)
        {
            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                daDebtSalePerson.Fill(dsCentral.DebtSalePerson, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
            }
            else
            {
                daDebtCustomer.Fill(dsCentral.DebtCustomer, dtpFromDate.DateTime.Date, dtpToDate.DateTime.Date);
            }
        }

        private void btnDebtAdjust_Click(object sender, EventArgs e)
        {
            DebtAdjustForm frmDebtAdjust = new DebtAdjustForm();
            frmDebtAdjust.ShowDialog();
            btnShow_Click(null, null);
        }

        private void btnCalculateDebt_Click(object sender, EventArgs e)
        {
            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                CalculateDebtSalePerson();
            }
            else
            {
                CalculateDebtCustomer();
            }
        }

        private void btnUnlock_Click(object sender, EventArgs e)
        {
            btnUnlock.Visible = false;
            btnLock.Visible = true;
            btnSave.Visible = true;

            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                colFirstDebt.OptionsColumn.AllowEdit = true;
                colFirstDebt.OptionsColumn.AllowFocus = true;
            }
            else
            {
                colFirstDebt1.OptionsColumn.AllowEdit = true;
                colFirstDebt1.OptionsColumn.AllowFocus = true;
            }

        }

        private void btnLock_Click(object sender, EventArgs e)
        {
            btnUnlock.Visible = true;
            btnLock.Visible = false;
            btnSave.Visible = false;

            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                colFirstDebt.OptionsColumn.AllowEdit = false;
                colFirstDebt.OptionsColumn.AllowFocus = false;
            }
            else
            {
                colFirstDebt1.OptionsColumn.AllowEdit = false;
                colFirstDebt1.OptionsColumn.AllowFocus = false;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (tabControl.SelectedTabPage == tabSalePerson)
            {
                bsDebtSalePerson.EndEdit();
                daDebtSalePerson.Update(dsCentral.DebtSalePerson);
            }
            else
            {
                bsDebtCustomer.EndEdit();
                daDebtCustomer.Update(dsCentral.DebtCustomer);
            }
        }
    }
}
